package com.hx.vending.service.impl;

import com.hx.vending.bean.MenuRole;
import com.hx.vending.bean.Role;
import com.hx.vending.dao.RoleMapper;
import com.hx.vending.service.IRoleService;
import com.hx.vending.util.Msg;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * Created by Administrator on 2019/1/2.
 */
@Service
public class RoleServiceImpl implements IRoleService {

    @Resource
    private RoleMapper roleMapper;

    @Override
    public List<Role> selectRoles(Role role) {
        return roleMapper.selectRoles(role);
    }

    @Override
    public int insertRole(Role role) {
        return roleMapper.insertRole(role);
    }

    @Override
    public int updateByPrimaryKey(Role role) {
        return roleMapper.updateByPrimaryKey(role);
    }

    @Override
    public Msg setAuthority(Integer roleId, String menuIds) {
        // 删除该角色所有的权限
        int result = roleMapper.deleteRoleMenuById(roleId);
        String[] strs = menuIds.split(",");
        Integer re = 0;
        for(int i = 0;i < strs.length;i++){
            MenuRole menuRole = new MenuRole();
            menuRole.setRoleMenuRoleId(roleId);
            menuRole.setRoleMenuMenuId(Integer.parseInt(strs[i]));
            int r = roleMapper.inserMenuRole(menuRole);
            re += r;
        }
        if(re > 0){
            return Msg.success();
        }
        return Msg.fail();
    }

    @Override
    public Msg delRoleById(String roleIds) {
        String[] strs = roleIds.split("-");
        for(int j =0;j < strs.length;j++){
            //删除角色
            int i = roleMapper.deleteRoleById(Integer.parseInt(strs[j]));
            if(i > 0){
                // 删除该角色所有的权限
                roleMapper.deleteRoleMenuById(Integer.parseInt(strs[j]));
            }
        }
        return Msg.success();
    }

    @Override
    public Role selectByPrimary(Role role) {
        return roleMapper.selectByPrimary(role);
    }

    @Override
    public String[] selectMenuByRole(Integer roleId) {
        return roleMapper.selectMenuByRole(roleId);
    }
}
